package com.test.sdk.pay.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.test.sdk.common.pojo.OnlineUser;
import com.test.sdk.common.pojo.Order;
import com.test.sdk.common.util.JsonUtil;
import com.test.sdk.common.util.TicketUtil;
import com.test.sdk.pay.AlipayConfig;
import com.test.sdk.service.service.OnlineService;
import com.test.sdk.service.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.jms.Queue;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class OrderController {
    @Reference
    private OnlineService onlineService;
    @Reference
    private OrderService orderService;
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    private Queue queue;

    @RequestMapping("page.html")
    public String page() {
        return "pay";
    }

    @RequestMapping("order.html")
    public void order(String ticket, Integer amount, Integer serverId, String roleId, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            String decodeTicket = TicketUtil.decode(ticket);
            OnlineUser user = onlineService.getOnlineUser(decodeTicket);
            if (user == null) {
                out.write("need login");
                return;
            }
            Order order = orderService.addOrder(user.getUserId(), amount, "sid=" + serverId + "&rid=" + roleId);
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, "RSA2");
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            Map<String, Object> param = new HashMap<>();
            param.put("out_trade_no", order.getOrderNum());
            param.put("product_code", "FAST_INSTANT_TRADE_PAY");
            param.put("total_amount", amount);
            param.put("subject", "测试订单");
            System.out.println(JsonUtil.getJSON(param));
            request.setBizContent(JsonUtil.getJSON(param));
            request.setReturnUrl(AlipayConfig.return_url);
            request.setNotifyUrl(AlipayConfig.notify_url);
            AlipayTradePagePayResponse result = alipayClient.pageExecute(request);
            if (result.isSuccess()) {
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }

            response.setContentType("text/html;charset=" + AlipayConfig.charset);
            out.println(result.getBody());//直接将完整的表单html输出到页面
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("return.html")
    public String returnPage(HttpServletRequest request) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码
            //该页面可做页面美工编辑
            //Order order = orderService.getOrderByOrderNum(orderNum);
            //判断交易状态，判断支付金额
            Order order = orderService.getOrderByNum(params.get("out_trade_no"));
            jmsMessagingTemplate.convertAndSend(queue, order.getOrderNum());

            System.out.println("交易状态：" + params.get("trade_status"));
            System.out.println("支付金额：" + params.get("total_amount"));
            return "success";
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
        } else {
            //该页面可做页面美工编辑
            return "fail";
        }
    }

    @RequestMapping("callback.html")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("===============================");
        System.out.println("支付回调");
        PrintWriter out = response.getWriter();
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        for (String s : params.keySet()) {
            System.out.println(s + "=" + params.get(s));
        }
        System.out.println("=======================");
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
    1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
        if (signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");


            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码
            Order order = orderService.getOrderByNum(out_trade_no);
            if (order == null) {
                out.println("fail");
                return;
            }
//            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            if (trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
//                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
//                //如果有做过处理，不执行商户的业务程序
                String sellerId = params.get("seller_id");
                if (!sellerId.equals(AlipayConfig.seller_id)) {//如果商户号一致，代表是我收的钱
                    out.println("fail");
                    return;
                }

                if (order.getPaySuccess() != null && order.getPaySuccess() == 1) {//如果是已经处理过的订单,则不处理
                    out.println("success");
                    return;
                }
                int totalFee = Float.valueOf(params.get("total_amount")).intValue();//交易金额，单位是元
                if (order.getAmount().equals(totalFee)) {//金额一致
                    order.setPaySuccess(1);//1代表成功
                    order.setResultDate(new Date());
                    order.setResultCode(trade_status);
                    order.setTradeNum(trade_no);
                    orderService.updateOrder(order);
                    jmsMessagingTemplate.convertAndSend(queue, order.getOrderNum());
                    //加话费、发游戏道具。。。。通知卖家。。。。
                    out.println("success");
                }
//                //注意：
//                //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。
            } else {
                order.setPaySuccess(0);
                order.setResultCode(trade_status);
                order.setResultDate(new Date());
                order.setTradeNum(trade_no);
                orderService.updateOrder(order);
            }
//            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
//            out.flush();
//            out.println("success");    //请不要修改或删除
            //////////////////////////////////////////////////////////////////////////////////////////
        } else {//验证失败
            System.out.println("签名失败");
            out.println("fail");
        }
    }

    @RequestMapping("test.html")
    public void test(HttpServletResponse response){
        try {
            response.getWriter().write("ok");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
